package com.sinodata.bsm.cicp.collector.weblogic9;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import javax.management.MBeanServerConnection;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;

import org.apache.log4j.Logger;

import com.sinodata.bsm.cicp.collector.Collector;
import com.sinodata.bsm.cicp.exception.CollectorException;
import com.sinodata.bsm.cicp.util.JmxUtil;
import com.sinodata.bsm.common.constants.DataTypeConstants;
import com.sinodata.bsm.common.vo.ResPropertyValue;

/**
 * 
 * <p>
 * Description: weblogic9 管理采集程序
 * </p>
 *
 * @author liulibo
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-11-12 16:26:07      liulibo        1.0         To create
 * </p>
 *
 * @since 
 * @see
 */
public class DomainCollector extends Collector {

    private static final Logger logger = Logger.getLogger(DomainCollector.class);

    private final HashMap time = new HashMap();

    //    private synchronized void addCounter(String key, String activationtime) {
    //        time.put(key, activationtime);
    //    }

    @SuppressWarnings("unchecked")
    @Override
    public List<ResPropertyValue> collect(String ip) throws CollectorException {
        String serverName = this.getParamMap().get("DomainName").trim();
        String key = serverName + ":" + ip;
        String port = this.getParamMap().get("port").trim();
        String[] propMetas = getPropMeta();
        ResPropertyValue propertyValueX = new ResPropertyValue();
        ResPropertyValue.PropValue[] propValues = new ResPropertyValue.PropValue[propMetas.length];

        List<ResPropertyValue> values = new ArrayList<ResPropertyValue>();
        ObjectName service;
        Object activationtime;
        Object domainConfiguration;
        JMXConnector connector = null;
        MBeanServerConnection connection = null;
        try {
            connector = JmxUtil.getConnection(ip, Integer.valueOf(port));
            connection = connector.getMBeanServerConnection();
            if (connection == null) {
                //   propValues[8] = ResPropertyValue.createPropValue("NO", propMetas[8]);
                propValues[8] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[8]);
                propertyValueX.setValues(propValues);
                values.add(propertyValueX);
                return values;
            }
            service = new ObjectName("com.bea:Name=DomainRuntimeService,Type=weblogic.management." + "mbeanservers.domainruntime.DomainRuntimeServiceMBean");
            Object domainRuntime = connection.getAttribute(service, "DomainRuntime");
            activationtime = connection.getAttribute((ObjectName) domainRuntime, "ActivationTime");
            domainConfiguration = connection.getAttribute(service, "DomainConfiguration");
            String attributeNames[] = new String[] { "AdministrationPortEnabled", "Clusters", "Servers", "AppDeployments", "AdministrationPort", "ProductionModeEnabled", "ClusterConstraintsEnabled" };
            Object attrValues[] = null;
            attrValues = JmxUtil.getAttribute(connection, (ObjectName) domainConfiguration, attributeNames);
            for (int i = 0; i < attrValues.length; i++) {
                if (attrValues[i] instanceof ObjectName[]) {
                    ObjectName[] objectNames = (ObjectName[]) attrValues[i];
                    StringBuffer sb = new StringBuffer();
                    for (ObjectName objectName : objectNames) {
                        String name = objectName.getKeyProperty("Name");
                        sb.append(name + " ");
                    }
                    propValues[i] = ResPropertyValue.createPropValue(sb.toString(), propMetas[i]);
                } else {
                    propValues[i] = ResPropertyValue.createPropValue(attrValues[i].toString(), propMetas[i]);
                }
            }
            propValues[7] = ResPropertyValue.createPropValue(activationtime.toString(), propMetas[7]);
            String temp = String.valueOf(time.get(key));
            if ((time.get(key) != null) && (!temp.equals(activationtime.toString()))) {
                //propValues[8] = ResPropertyValue.createPropValue("NO", propMetas[8]);
                propValues[8] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[8]);
            } else {
                //  propValues[8] = ResPropertyValue.createPropValue("YES", propMetas[8]);
                propValues[8] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_TRUE, propMetas[8]);
            }
            time.remove(key);
            time.put(key, activationtime);
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
            return values;
        } catch (IOException e) {
            logger.error("IOException", e);
            //propValues[8] = ResPropertyValue.createPropValue("NO", propMetas[8]);
            propValues[8] = ResPropertyValue.createPropValue(DataTypeConstants.BOOLEAN_VALUE_FALSE, propMetas[8]);
            propertyValueX.setValues(propValues);
            values.add(propertyValueX);
            return values;
        } catch (Exception e) {
            logger.error("failed to collect by DomainCollector", e);
            throw new CollectorException(e);
        } finally {
            JmxUtil.closeConnector(connector);
        }
    }

    @Override
    public String[] getParamMeta() {
        return new String[] { "DomainName", "port" };
    }

    @Override
    public String[] getPropMeta() {
        //return new String[] { "AdministrationPortEnabled", "Clusters", "Servers", "AppDeployments", "AdministrationPort", "ProductionModeEnabled", "ClusterConstraintsEnabled", "activationtime", "isConnect" };
        return new String[] { "$1", "$2", "$3", "$4", "$5", "$6", "$7", "$8", "$9" };

    }
}
